// import { createRouter, createWebHistory } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'
import Login from '../views/login.vue'
import { ElMessage } from 'element-plus'

// const router = createRouter({
//   history: createWebHistory(),
//   mode: 'hash',
  // routes: [
  //   {
  //     path: '/login',
  //     name: 'login',
  //     component: Login
  //   },
  //   {
  //     path: '/',
  //     name: 'home',
  //     component: HomeView,
  //     children: [
  //       {
  //         path: 'about',
  //         component: AboutView
  //       }
  //     ]
  //   }, 
  // ]
// })
const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    name: 'home',
    component: HomeView,
    children: [
      {
        path: 'about',
        component: AboutView
      }
    ]
  }, 
]
const router = createRouter({
  history: createWebHashHistory(),
  routes
});


// 添加路由拦截
router.beforeEach((to, from, next) => {
  if (to.name !== 'login' && !isAuthenticated()) {
    next({ name: 'login' }); // 如果未登录且不是跳转到登录页，则跳转到登录页
  } else {
    next(); // 其他情况正常跳转
  }
});

function isAuthenticated() {
  // 在这里判断用户是否已经登录，可以根据自己的逻辑来实现
  // 如果已登录返回true，未登录返回false
  const user = window.sessionStorage.getItem('user')
  if (user) {
    return true
  }
  else {
    ElMessage.error('登录失效, 请重新登录')
    return false
  }
  
}
export default router
